<template>
  <div class="product-detail-container">
    <div v-if="loading" class="loading-container">
      <el-skeleton style="width: 100%" :rows="10" animated />
    </div>

    <template v-else>
      <div class="product-header">
        <el-page-header @back="goBack" :title="product.name" />
      </div>

      <div class="product-content">
        <!-- 修改媒体展示区域 -->
        <div class="product-media-section">
          <!-- 主媒体展示区域 -->
          <div class="product-main-media">
            <!-- 视频展示 -->
            <div v-if="activeMedia === 'video' && product.videoUrl" class="media-container">
              <video :src="product.videoUrl" controls class="product-video"></video>
            </div>
            <!-- 图片展示 -->
            <div v-else class="media-container">
              <img 
                v-if="product.mainImageUrl && (currentImageIndex === 0 || !additionalImages[currentImageIndex-1])" 
                :src="product.mainImageUrl" 
                :alt="product.name" 
                class="display-image"
              >
              <img 
                v-else-if="additionalImages[currentImageIndex-1]"
                :src="additionalImages[currentImageIndex-1]" 
                :alt="product.name" 
                class="display-image"
              >
            </div>
          </div>
          
          <!-- 媒体切换按钮 -->
          <div class="media-controls">
            <el-button-group>
              <el-button 
                :type="activeMedia === 'image' ? 'primary' : 'default'" 
                @click="switchMedia('image')"
                :disabled="!product.mainImageUrl"
              >
                图片
              </el-button>
              <el-button 
                :type="activeMedia === 'video' ? 'primary' : 'default'" 
                @click="switchMedia('video')"
                :disabled="!product.videoUrl"
              >
                视频
              </el-button>
            </el-button-group>
          </div>
          
          <!-- 缩略图预览 -->
          <div class="media-thumbnails" v-if="product.mainImageUrl">
            <div 
              class="thumbnail" 
              :class="{ active: activeMedia === 'image' && currentImageIndex === 0 }"
              @click="showImage(0)"
            >
              <img :src="product.mainImageUrl" :alt="product.name">
            </div>
            <div 
              v-for="(img, index) in additionalImages" 
              :key="index"
              class="thumbnail"
              :class="{ active: activeMedia === 'image' && currentImageIndex === index + 1 }"
              @click="showImage(index + 1)"
            >
              <img :src="img" :alt="product.name">
            </div>
            <div 
              v-if="product.videoUrl" 
              class="thumbnail video-thumbnail"
              :class="{ active: activeMedia === 'video' }"
              @click="switchMedia('video')"
            >
              <div class="video-icon">
                <i class="el-icon-video-play"></i>
              </div>
            </div>
          </div>
        </div>
        
        <!-- 其余内容保持不变 -->
        <div class="product-info-section">
          <h1 class="product-title">{{ product.name }}</h1>

          <!-- 宠物商品信息展示 -->
          <!-- ... 保持不变 ... -->
          <!-- 宠物商品信息展示 -->
          <div v-if="isPetProduct" class="product-basic-info">
            <div class="info-item" v-if="product.breed">
              <span class="label">品种:</span>
              <span class="value">{{ product.breed }}</span>
            </div>
            <div class="info-item" v-if="product.age">
              <span class="label">年龄:</span>
              <span class="value">{{ product.age }}</span>
            </div>
            <div class="info-item" v-if="product.sex">
              <span class="label">性别:</span>
              <span class="value">{{ product.sex }}</span>
            </div>
            <div class="info-item" v-if="product.weight">
              <span class="label">体重:</span>
              <span class="value">{{ product.weight }}kg</span>
            </div>
            <div class="info-item" v-if="product.color">
              <span class="label">颜色:</span>
              <span class="value">{{ product.color }}</span>
            </div>
            <div class="info-item">
              <span class="label">价格:</span>
              <span class="value price">¥ {{ product.price }}</span>
            </div>
            <div class="info-item" v-if="product.stock !== undefined">
              <span class="label">库存:</span>
              <span class="value">{{ product.stock }}只</span>
            </div>
          </div>

          <!-- 宠物用品信息展示 -->
          <div v-else class="product-basic-info">
            <div class="info-item">
              <span class="label">价格:</span>
              <span class="value price">¥ {{ product.price }}</span>
            </div>
            <div class="info-item" v-if="product.stock !== undefined">
              <span class="label">库存:</span>
              <span class="value">{{ product.stock }}件</span>
            </div>
          </div>

          <div class="product-description">
            <h2>{{ isPetProduct ? '宠物描述' : '商品描述' }}</h2>
            <p v-if="product.description">{{ product.description }}</p>
            <p v-else class="no-data">暂无描述信息</p>
          </div>

          <!-- 健康信息仅对宠物显示 -->
          <div v-if="isPetProduct" class="health-info">
            <h2>健康信息</h2>
            <div v-if="product.healthInfo">
              <p>{{ product.healthInfo }}</p>
            </div>
            <div v-else class="no-data">
              <p>暂无健康信息</p>
            </div>
          </div>

          <div class="store-section" v-if="store">
            <div class="store-info">
              <div class="store-header">
                <div>
                  <h2>{{ store.name }}</h2>
                  <p v-if="store.description">{{ store.description }}</p>
                </div>
              </div>
              <el-button type="primary" size="small" @click="viewStore" class="store-btn">
                查看店铺全部{{ isPetProduct ? '宠物' : '商品' }}
              </el-button>
            </div>
          </div>

          <div class="product-actions">
            <el-button type="default" @click="addToFavorites">收藏</el-button>
            <el-button type="primary" @click="addToCart" :loading="adding">
              加入购物车
            </el-button>
          </div>
        </div>

        <div class="reviews-section">
          <h2>用户评价</h2>
          <div v-if="product.reviewCount > 0" class="rating-summary">
            <div class="rating-score">{{ product.averageRating || 0 }}</div>
            <div class="rating-stars">{{ generateStars(product.averageRating || 0) }}</div>
            <div class="rating-count">基于 {{ product.reviewCount }} 条评价</div>
          </div>
          <div v-else class="no-reviews">
            <p>暂无评价</p>
          </div>

          <!-- 添加评论表单 -->
          <div class="add-review-section">
            <h3>发表评价</h3>
            <el-form :model="reviewForm" label-position="top">
              <el-form-item label="评分">
                <el-rate
                  v-model="reviewForm.rating"
                  :colors="['#99A9BF', '#F7BA2A', '#FF9900']"
                  :texts="['1分', '2分', '3分', '4分', '5分']"
                  show-text
                />
              </el-form-item>
              <el-form-item label="评价内容">
                <el-input
                  type="textarea"
                  v-model="reviewForm.content"
                  :rows="4"
                  placeholder="请输入您对商品的评价..."
                />
              </el-form-item>
              <el-form-item label="上传图片">
                <el-upload
                  action="#"
                  list-type="picture-card"
                  :auto-upload="false"
                  :on-change="handleImageChange"
                  :limit="5"
                  :file-list="reviewImages"
                >
                  <template #default>
                    <el-icon><Plus /></el-icon>
                  </template>
                </el-upload>
              </el-form-item>
              <el-form-item>
                <el-button type="primary" @click="submitReview" :loading="submitting">提交评价</el-button>
              </el-form-item>
            </el-form>
          </div>

          <div v-if="reviews && reviews.records && reviews.records.length > 0" class="review-list">
            <div class="review-item" v-for="(review, index) in reviews.records" :key="index">
              <div class="reviewer-info">
                <img
                  :src="review.userAvatarUrl || '/assets/default-avatar.jpg'"
                  :alt="review.userNickname"
                  class="reviewer-avatar"
                >
                <div class="reviewer-name">{{ review.userNickname || '匿名用户' }}</div>
                <div class="review-date">{{ formatDate(review.createdAt) }}</div>
              </div>
              <div class="review-stars">{{ generateStars(review.rating) }}</div>
              <div class="review-content">{{ review.content || '用户未留下评价内容' }}</div>
              <div class="review-images" v-if="review.imageUrls && review.imageUrls.length">
                <img
                  v-for="(img, imgIndex) in review.imageUrls"
                  :key="imgIndex"
                  :src="img"
                  class="review-image"
                  @click="previewImage(img)"
                >
              </div>
            </div>
          </div>
          <div v-else-if="product.reviewCount > 0" class="no-data">
            <p>评价加载中...</p>
          </div>

          <div v-if="reviews && reviews.total > reviews.records.length" class="view-more-reviews">
            <el-button type="text" @click="loadMoreReviews">查看更多评价 ></el-button>
          </div>
        </div>
      </div>
    </template>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, computed } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import axios from 'axios'
import { ElMessage } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'

const route = useRoute()
const router = useRouter()
const productId = ref(route.params.id)
const loading = ref(true)
const adding = ref(false)
const quantity = ref(1)

// 新增媒体相关变量
const activeMedia = ref('video') // 默认显示视频，而不是'image'
const currentImageIndex = ref(0)
const additionalImages = ref<string[]>([])
const carousel = ref<any>(null)

// 切换媒体类型
const switchMedia = (type: 'image' | 'video') => {
  activeMedia.value = type
  // 如果切换到图片模式，确保显示当前选中的图片
  if (type === 'image' && carousel.value) {
    carousel.value.setActiveItem(currentImageIndex.value)
  }
}

// 显示指定索引的图片
const showImage = (index: number) => {
  if (activeMedia.value !== 'image') {
    activeMedia.value = 'image'
  }
  currentImageIndex.value = index
  if (carousel.value) {
    carousel.value.setActiveItem(index)
  }
}

const product = ref({
  id: 0,
  name: '',
  description: '',
  price: 0,
  mainImageUrl: '',
  videoUrl: '',
  imageUrls: [] as string[],
  stock: 0,
  breed: '',
  age: '',
  sex: '',
  weight: null,
  color: '',
  healthInfo: '',
  averageRating: 0,
  reviewCount: 0,
  isPet: false // 如果后端添加了这个字段
})
const store = ref<any>(null)
const reviews = ref<any>(null)

// 评论表单数据
const reviewForm = ref({
  productId: 0,
  rating: 5,
  content: '',
  imageUrls: [] as string[]
})

// 评论图片上传相关
const reviewImages = ref<any[]>([])
const submitting = ref(false)

// 判断是否为宠物商品
const isPetProduct = computed(() => {

  // 方案二：根据宠物特有属性判断
  return !!(product.value.breed || product.value.age || product.value.sex)
})

// 生成星级显示
const generateStars = (rating: number) => {
  const fullStars = Math.floor(rating)
  const hasHalfStar = rating % 1 >= 0.5
  const emptyStars = 5 - fullStars - (hasHalfStar ? 1 : 0)

  return '★'.repeat(fullStars) +
         (hasHalfStar ? '☆' : '') +
         '☆'.repeat(emptyStars)
}

// 格式化日期
const formatDate = (dateString: string) => {
  if (!dateString) return ''
  const date = new Date(dateString)
  return date.toLocaleDateString('zh-CN')
}

// 预览图片
const previewImage = (imageUrl: string) => {
  // 可以使用Element Plus的图片预览组件
  window.open(imageUrl, '_blank')
}

// 返回上一页
const goBack = () => {
  router.back()
}

// 查看店铺
const viewStore = () => {
  if (store.value && store.value.id) {
    router.push(`/store/${store.value.id}`)
  } else {
    ElMessage.warning('店铺信息不完整')
  }
}

// 添加到收藏
const addToFavorites = () => {
  ElMessage.success('收藏成功')
}

// 获取商品详情
const fetchProductDetail = async () => {
  try {
    loading.value = true
    console.log('开始获取商品详情，ID:', productId.value)

    const response = await axios.get(`/api/user/products/${productId.value}`)
    console.log('商品详情响应:', response.data)

    // 使用后端返回的真实数据
    product.value = response.data
    
    // 设置评论表单的商品ID
    reviewForm.value.productId = Number(productId.value)

    // 处理图片和视频
    if (response.data.imageUrls && response.data.imageUrls.length) {
      additionalImages.value = response.data.imageUrls
    } else {
      // 如果后端没有提供 imageUrls 数组，创建一个空数组
      additionalImages.value = []
    }
    
    // 设置默认媒体类型
    if (response.data.videoUrl) {
      activeMedia.value = 'video' // 保持视频优先
    } else {
      activeMedia.value = 'image' // 只有在没有视频时才显示图片
    }

    // 获取商店信息
    if (response.data.store) {
      store.value = response.data.store
    }

    // 获取评价信息
    if (response.data.reviews) {
      reviews.value = response.data.reviews
    }

    loading.value = false
    console.log('商品详情加载完成:', product.value)

  } catch (error) {
    console.error('获取商品详情失败:', error)
    ElMessage.error('获取商品详情失败，请稍后重试')
    loading.value = false
  }
}

// 加载更多评价
const loadMoreReviews = async () => {
  try {
    const currentPage = reviews.value.current + 1
    // 修改API路径
    const response = await axios.get(`/api/user/reviews/product/${productId.value}`, {
      params: {
        current: currentPage,
        size: 5
      }
    })

    // 追加新的评价数据
    reviews.value.records.push(...response.data.records)
    reviews.value.current = response.data.current
  } catch (error) {
    console.error('加载更多评价失败:', error)
    ElMessage.error('加载更多评价失败')
  }
}

// 添加到购物车
const addToCart = async () => {
  // 检查是否登录
  const token = localStorage.getItem('token')
  if (!token) {
    router.push({
      path: '/login',
      query: { redirect: route.fullPath }
    })
    return
  }

  try {
    adding.value = true
    await axios.post('/api/user/cart/items', {
      productId: product.value.id,
      quantity: quantity.value
    })

    ElMessage.success('成功加入购物车')
  } catch (error) {
    console.error('添加购物车失败:', error)
    ElMessage.error('添加购物车失败，请稍后重试')
  } finally {
    adding.value = false
  }
}

// 处理图片变更
const handleImageChange = (file: any, fileList: any[]) => {
  reviewImages.value = fileList
}

// 上传图片到服务器
const uploadImage = async (file: File) => {
  try {
    const formData = new FormData()
    formData.append('file', file)
    
    const response = await axios.post('/api/user/files/upload/image', formData, {
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    })
    
    return response.data.fileUrl
  } catch (error) {
    console.error('上传图片失败:', error)
    throw error
  }
}

// 提交评价
const submitReview = async () => {
  // 检查是否登录
  const token = localStorage.getItem('token')
  if (!token) {
    router.push({
      path: '/login',
      query: { redirect: route.fullPath }
    })
    return
  }
  
  // 验证评分
  if (!reviewForm.value.rating) {
    ElMessage.warning('请选择评分')
    return
  }
  
  try {
    submitting.value = true
    
    // 上传图片并获取URL列表
    const imageUrls: string[] = []
    if (reviewImages.value.length > 0) {
      for (const fileItem of reviewImages.value) {
        if (fileItem.raw) {
          const imageUrl = await uploadImage(fileItem.raw)
          imageUrls.push(imageUrl)
        }
      }
    }
    
    // 构建评价数据
    const reviewData = {
      productId: reviewForm.value.productId,
      rating: reviewForm.value.rating,
      content: reviewForm.value.content,
      imageUrls: imageUrls
    }
    
    // 提交评价
    await axios.post('/api/user/reviews', reviewData)
    
    ElMessage.success('评价提交成功')
    
    // 重置表单
    reviewForm.value.rating = 5
    reviewForm.value.content = ''
    reviewImages.value = []
    
    // 刷新评价列表
    fetchProductDetail()
    
  } catch (error) {
    console.error('提交评价失败:', error)
    ElMessage.error('提交评价失败，请稍后重试')
  } finally {
    submitting.value = false
  }
}

onMounted(() => {
  fetchProductDetail()
})
</script>

<style scoped>
/* 保留原有样式 */
.product-detail-container {
  width: 100%;
  min-height: 100vh;
  margin: 0;
  padding: 0;
  font-family: Arial, sans-serif;
  background-color: #fff;
}

.loading-container {
  max-width: 1200px;
  margin: 0 auto;
  background-color: white;
  padding: 20px;
  border-radius: 4px;
}

.product-header {
  margin-bottom: 20px;
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px 20px 0 20px;
}

.product-content {
  display: flex;
  flex-direction: column;
  background-color: white;
  max-width: 1200px;
  margin: 0 auto;
  padding: 0 20px 20px 20px;
}

.product-banner {
  width: 100%;
  height: 350px;
  overflow: hidden;
  margin-bottom: 30px;
  border-radius: 8px;
}

.product-banner img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.product-info-section {
  margin-bottom: 30px;
}

.product-title {
  font-size: 28px;
  font-weight: bold;
  margin-bottom: 20px;
  color: #333;
}

.product-basic-info {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 15px;
  margin-bottom: 30px;
  padding: 20px;
  background-color: #f9f9f9;
  border-radius: 8px;
}

.info-item {
  display: flex;
}

.label {
  font-weight: bold;
  margin-right: 10px;
  min-width: 60px;
}

.value {
  color: #666;
}

.value.price {
  color: #f56c6c;
  font-weight: bold;
  font-size: 18px;
}

.product-description {
  margin-bottom: 30px;
}

.product-description h2 {
  font-size: 20px;
  margin-bottom: 15px;
  color: #333;
}

.product-description p {
  line-height: 1.6;
  color: #666;
}

.health-info {
  margin-bottom: 30px;
}

.health-info h2 {
  font-size: 20px;
  margin-bottom: 15px;
  color: #333;
}

.health-columns {
  display: flex;
  gap: 40px;
}

.health-column {
  flex: 1;
}

.health-column h3 {
  font-size: 16px;
  margin-bottom: 10px;
  color: #333;
}

.health-column ul {
  list-style-type: none;
  padding: 0;
}

.health-column li {
  margin-bottom: 8px;
  position: relative;
  padding-left: 20px;
  color: #666;
}

.health-column li::before {
  content: "•";
  position: absolute;
  left: 0;
  color: #409eff;
  font-weight: bold;
}

.store-section {
  margin-bottom: 30px;
  padding: 20px;
  background-color: #f9f9f9;
  border-radius: 8px;
}

.store-info h2 {
  font-size: 18px;
  margin-bottom: 10px;
  color: #333;
}

.store-info p {
  margin-bottom: 15px;
  color: #666;
}

.store-btn {
  margin-top: 10px;
}

.product-actions {
  display: flex;
  gap: 15px;
  margin-bottom: 30px;
}

.reviews-section {
  margin-bottom: 40px;
}

.reviews-section h2 {
  font-size: 20px;
  margin-bottom: 20px;
  color: #333;
}

.rating-summary {
  display: flex;
  align-items: center;
  margin-bottom: 30px;
}

.rating-score {
  font-size: 36px;
  font-weight: bold;
  margin-right: 20px;
  color: #ff9800;
}

.rating-stars {
  color: #ff9800;
  font-size: 20px;
  margin-right: 20px;
}

.rating-count {
  color: #999;
}

/* 添加评论表单样式 */
.add-review-section {
  margin: 30px 0;
  padding: 20px;
  background-color: #f9f9f9;
  border-radius: 8px;
}

.add-review-section h3 {
  font-size: 18px;
  margin-bottom: 20px;
  color: #333;
}

.review-list {
  margin-bottom: 20px;
}

.review-item {
  border-bottom: 1px solid #eee;
  padding: 20px 0;
}

.reviewer-info {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
}

.reviewer-avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  margin-right: 10px;
  object-fit: cover;
}

.reviewer-name {
  font-weight: bold;
  margin-right: 15px;
}

.review-date {
  color: #999;
  font-size: 14px;
}

.review-stars {
  color: #ff9800;
  margin-bottom: 10px;
}

.review-content {
  line-height: 1.6;
  margin-bottom: 15px;
  color: #666;
}

.review-images {
  display: flex;
  gap: 10px;
  margin-top: 10px;
}

.review-image {
  width: 80px;
  height: 80px;
  object-fit: cover;
  border-radius: 4px;
  cursor: pointer;
}

.view-more-reviews {
  text-align: center;
}

/* 修改媒体展示相关样式 */
.product-media-section {
  width: 100%;
  margin-bottom: 30px;
}

.product-main-media {
  width: 100%;
  height: 400px; /* 可以根据需要调整高度 */
  overflow: hidden;
  margin-bottom: 15px;
  border-radius: 8px;
  background-color: #f5f5f5;
  position: relative;
  display: flex;
  justify-content: center;
  align-items: center;
}

.media-container {
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 10px;
}

.product-video {
  max-width: 100%;
  max-height: 100%;
  object-fit: contain; /* 保持宽高比，确保视频完全可见 */
  background-color: #000;
}

.carousel-image {
  max-width: 100%;
  max-height: 100%;
  object-fit: contain; /* 保持宽高比，确保图片完全可见 */
}

.display-image {
  max-width: 100%;
  max-height: 100%;
  object-fit: contain;
  display: block;
  margin: 0 auto;
}

/* 修改轮播图样式，确保图片正常显示 */
/* 添加深度选择器修改Element Plus轮播图样式 */
:deep(.el-carousel__container) {
  height: 100%;
}

:deep(.el-carousel__item) {
  display: flex;
  justify-content: center;
  align-items: center;
  background-color: #f5f5f5;
}

:deep(.el-carousel__item--card) {
  border: none;
}

.media-controls {
  display: flex;
  justify-content: center;
  margin: 15px 0;
}

.media-controls .el-button {
  padding: 10px 25px; /* 增大按钮 */
  font-size: 16px; /* 增大字体 */
  font-weight: bold; /* 加粗字体 */
}

.media-thumbnails {
  display: flex;
  flex-wrap: wrap; /* 允许换行 */
  gap: 15px; /* 增加间距 */
  padding: 10px 0;
  margin-bottom: 20px;
  justify-content: center; /* 居中显示 */
}

.thumbnail {
  width: 80px; /* 增大缩略图 */
  height: 80px;
  border-radius: 4px;
  overflow: hidden;
  cursor: pointer;
  border: 2px solid transparent;
  transition: all 0.3s ease;
}

.thumbnail.active {
  border-color: #409eff;
  transform: scale(1.1); /* 选中时略微放大 */
}

.thumbnail img {
  width: 100%;
  height: 100%;
  object-fit: cover; /* 改为cover而不是contain，确保图片填满容器不缩小 */
}

.product-main-media {
  width: 100%;
  height: 450px; /* 保持足够的高度 */
  overflow: hidden;
  margin-bottom: 15px;
  border-radius: 8px;
  background-color: #f5f5f5;
  position: relative;
}

/* 修改轮播图样式，确保图片正常显示 */
:deep(.el-carousel__item) {
  display: flex;
  justify-content: center;
  align-items: center;
  background-color: #f5f5f5;
}

:deep(.el-carousel__item--card) {
  border: none;
}

.media-controls {
  display: flex;
  justify-content: center;
  margin: 15px 0;
}

.media-controls .el-button {
  padding: 10px 25px; /* 增大按钮 */
  font-size: 16px; /* 增大字体 */
  font-weight: bold; /* 加粗字体 */
}

.media-thumbnails {
  display: flex;
  gap: 15px; /* 增加间距 */
  overflow-x: auto;
  padding: 10px 0;
  margin-bottom: 20px;
  justify-content: center; /* 居中显示 */
}

.thumbnail {
  width: 80px; /* 增大缩略图 */
  height: 80px;
  border-radius: 4px;
  overflow: hidden;
  cursor: pointer;
  border: 2px solid transparent;
  transition: all 0.3s ease;
}

.thumbnail.active {
  border-color: #409eff;
  transform: scale(1.1); /* 选中时略微放大 */
}

.thumbnail img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.video-thumbnail {
  background-color: #000;
  display: flex;
  justify-content: center;
  align-items: center;
  color: white;
}

.video-icon {
  font-size: 32px; /* 增大图标 */
}

/* 响应式调整 */
@media (max-width: 768px) {
  .product-main-media {
    height: 300px; /* 移动端适当调整 */
  }
  
  .thumbnail {
    width: 60px;
    height: 60px;
  }
}
</style>
